package com.xy6.jvm.atomic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

/**
 * AtomicReference示例
 * 
 * @author zhang
 *
 */
public class AtomicReferenceTest {

	private static AtomicReference<Integer> ar = new AtomicReference<>(0);

	public static void test1() throws InterruptedException {
		int t = 100;
		final int c = 100;
		final CountDownLatch latch = new CountDownLatch(t);
		for (int i = 0; i < t; i++) {
			new Thread(new Runnable(){
				@Override
				public void run(){
					for(int i=0; i<c; i++){
						while(true){
							Integer temp = ar.get();
							if(ar.compareAndSet(temp, temp + 1)){
								break;
							}
						}
					}
					latch.countDown();
				}
			}).start();
		}
		latch.await();
		System.out.println(latch.getCount());
		// 10000000
		System.out.println(ar.get());
	}

	public static void main(String[] args) throws InterruptedException {
		test1();
	}

}
